// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
}) // 使用当前云环境

const db = cloud.database()

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  let data = null
  if (typeof event.order_amount_total !== "number" || isNaN(event.order_amount_total)) {
    event.order_amount_total = parseFloat(event.order_amount_total);
  } 
  if(event.flag=='add'){
    data = await db.collection('SJBL_Orders').add({
      data: {
        order_no: event.order_no,
        order_date:Date.now(),
        order_status: event.order_status,
        product_no: event.product_no,
        product_count: event.product_count,
        order_amount_total: event.order_amount_total,
        logistics_fee: event.logistics_fee,
        address_id: event.address_id,
        remarks: event.remarks,
        user_openid: event.user_openid,
        delivery_time: '',
        gategory: event.gategory,
        size: event.size,
        order_settlement_time: ''
      }
    })
  }else{
    data = await db.collection('SJBL_Orders').where({
      order_no: event.order_no
    }).update({
      data: {
        order_status: event.order_status
      }
    })
  }
  return {
    event,
    openid: wxContext.OPENID,
    appid: wxContext.APPID,
    unionid: wxContext.UNIONID,
    data
  }
}

